import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { customizedCouponStatusArr, userCouponStatusArr } from '../customized-coupon-manage.pipe';
import { PermissionService } from '../../../../service/permission.service';
import { CustomizedCouponService } from '../services/customized-coupon.service';

@Component({
  selector: 'app-customized-coupon-list',
  templateUrl: './customized-coupon-list.component.html',
  styleUrls: ['./customized-coupon-list.component.scss']
})
export class CustomizedCouponListComponent implements OnInit {
  // 路由缓存恢复时
  static updateCache: any = null;

  searchOptions = [
    { type: 1, labelText: '优惠券名称', valueKey: 'name', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'statusStr',
      value: [],
      multiple: true,
      selectOptions: [...customizedCouponStatusArr],
    }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 审核Modal
  isExamineVisible = false;
  examineItem: any = {};
  examineParams = {
    remark: ''
  };

  // 手动发券
  releaseVisible = false;
  releaseLoading = false;
  opreaItem: any = {};

  /**
   * 用户优惠券 Modal
   * ----------------------------------------------------------------
   */
  isUserVisible = false;
  userCouponItem: any = {};
  userCouponTableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };
  userLoading = false;
  userCouponSearch = [
    // { type: 1, labelText: '优惠券ID', valueKey: 'couponNo', value: '' },
    { type: 1, labelText: '用户优惠券ID', valueKey: 'id', value: '' },
    { type: 1, labelText: '用户ID', valueKey: 'userInfo', value: '', placeholder: '请输入用户ID' },
    { type: 1, labelText: '关联单号', valueKey: 'orderNum', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'status',
      value: '',
      multiple: false,
      notTostr: false,
      selectOptions: [...userCouponStatusArr],
    },
    { type: 3, labelText: '领取时间', valueKey: ['getBeginTime', 'getEndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '过期时间', valueKey: ['endBeginTime', 'endTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '使用时间', valueKey: ['useBeginTime', 'useEndTime'], value: [], isTimeSelect: true }
  ];
  userCouponParams: any = {};

  categoryOptions: any = [];

  /**
   * 用户优惠券Table Check
   * -----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  constructor(
    private message: NzMessageService,
    private router: Router,
    private modal: NzModalService,
    public permission: PermissionService,
    private services: CustomizedCouponService
  ) { }

  ngOnInit(): void {
    this.loadAdzGoodTypeList();
    CustomizedCouponListComponent.updateCache = () => {
      this.loadAdzGoodTypeList();
      this.loadTable();
    }
  }

  // 查询适用品类
  async loadAdzGoodTypeList() {
    const {code, data, message}: any = await this.services.getAdzGoodTypeList();
    if (code === 0) {
      this.categoryOptions = data || [];
    } else {
      this.message.error(message);
    }
  }

  // Coupon List
  async loadTable() {
    let params = {
      ...this.searchParams,
      pageNum: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const res: any = await this.services.getMakeupCouponList(params);
    this.tableParams.loading = false;

    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * 页面跳转
   * @param type 0：新增 1：编辑 2：查看 3：复制
   * @param item 
   */
  jumpPage(type: number, item?: any) {
    let url = type === 2 ? '/customization/customized-coupon-details' : '/customization/customized-coupon-edit';
    let obj: any = {
      type
    };
    if ([1, 2, 3].includes(type)) {
      obj.id = item.id
    }
    this.router.navigate([url],{
      queryParams: obj
    })
  }

  /**
   * 审核
   * @param item 
   * ----------------------------------------------------------------
   */
  showExamineModal(item: any) {
    this.examineParams.remark = '';
    this.examineItem = item;
    this.isExamineVisible = true;
  }

  // Type 1：通过 7：不通过
  async subExamine(type: number) {
    if (type === 7 && !this.examineParams.remark) {
      this.message.warning('请输入审核意见');
      return
    }
    let params = {
      id: this.examineItem.id,
      reviewRemark: this.examineParams.remark,
      status: type
    }
    const { code, message }: any = await this.services.examineCouponItem(params);

    if (code === 0) {
      this.isExamineVisible = false;
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(message);
    }
  }

  /**
   * 停止
   * @param item
   * ----------------------------------------------------------------
   */
  async stopItem(item: any) {
    const res: any = await this.services.stopCouponItem(item.id);
    if (res.code === 0) {
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 启用
   * @param item 
   */
  async enableItem(item: any) {
    let params = {
      id: item.id,
      status: 1
    }
    const { code, message }: any = await this.services.examineCouponItem(params);
    if (code === 0) {
      this.message.success('启用成功');
      this.loadTable();
    } else {
      this.message.error(message);
    }
  }

  /**
   * 删除
   * @param item
   * ----------------------------------------------------------------
   */
  async deleteItem(item: any) {
    const { code, message }: any = await this.services.deleteCouponItem(item.id);
    if (code === 0) {
      this.message.success('删除成功');
      this.loadTable();
    } else {
      this.message.error(message);
    }
  }

  /**
   * 手动发放
   * ----------------------------------------------------------------
   */
  showCouponModal(item: any) {
    this.opreaItem = item;
    this.releaseVisible = true;
  }

  async submitManual(val: any) {
    this.loadTable();
  }

  /**
   * ----------------------------------------------------------------
   * 用户优惠券 Modal
   * ----------------------------------------------------------------
   */
  async loadUserCouponTable() {
    let params = {
      ...this.userCouponParams,
      couponNo: this.userCouponItem.no,
      type: 4,
      pageNum: this.userCouponTableParams.page,
      pageSize: this.userCouponTableParams.pageSize
    }
    this.userCouponTableParams.loading = true;
    const {code, data, message}: any = await this.services.getUserCouponList(params);
    this.userCouponTableParams.loading = false;
    
    if (code === 0) {
      const {list, total} = data || {};
      this.userCouponTableParams.tableData = list || [];
      this.userCouponTableParams.total = total || 0;
    } else {
      this.message.error(message);
    }
  }

  // user PageIndex Change
  userIndexChange(index: number) {
    this.userCouponTableParams.page = index;
    this.loadUserCouponTable();
  }
  
  // user PageSize Change
  userSizeChange(sizeNum: number) {
    this.userCouponTableParams.page = 1;
    this.userCouponTableParams.pageSize = sizeNum;
    this.loadUserCouponTable();
  }

  couponQueryResetData(params: any) {
    this.userCouponParams = params;
    this.userCouponTableParams.page = 1;
    this.loadUserCouponTable();
  }

  showUserCouponModal(item: any) {
    this.userCouponItem = item;
    this.isUserVisible = true;
  }

  batchWithdrawCoupon() {
    if (!this.setOfCheckedId.size) {
      this.message.warning('请先选择所需撤回项');
      return
    }
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: `确认撤回所选中的 <b style="color: red;">${this.setOfCheckedId.size}</b> 张优惠券?`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.withdrawInterface([...this.setOfCheckedId])
      },
      nzCancelText: '取消'
    });
  }

  withdrawCoupon(item: any) {
    this.withdrawInterface([item.id]);
  }

  async withdrawInterface(ids: any[]) {
    let params: any = {
      // remark: this.withdrawParams.remark,
      type: 4,
      ids: ids
    }
    const res: any = await this.services.stopUserCoupon(params);

    if (res.code === 0) {
      this.message.success('撤回成功');
      this.setOfCheckedId.clear();
      this.loadUserCouponTable();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 用户优惠券 Check
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData
      .filter(({ status }) => status === 1)
      .forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.listOfCurrentPageData.filter(({ status }) => status === 1);
    this.checked = listOfEnabledData.every(item => this.setOfCheckedId.has(item.id)) && listOfEnabledData.length > 0;
    this.indeterminate = listOfEnabledData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  // 适用品类
  categoryTypeFilter(str: string) {
    if (this.isEmpty(str)) {
      return '-'
    } else {
      if (str === '0') {
        return '全部'
      } else {
        let strArr = str.split(',').map((m: any) => +m);
        let tempArr: any = [];
        this.categoryOptions.forEach((item: any) => {
          if (strArr.includes(item.groupId)) {
            tempArr.push(item.textureName);
          }
        })
        return tempArr.join('、');
      }
    }
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }
}
